<?php
ini_set('date.timezone','Asia/Shanghai');
//error_reporting(E_ERROR); 

//require_once '../sql.php';
require_once (dirname(__FILE__) . "/../../common.inc.php");
require_once DEDEDATA."/payment/wpay.php"; 
require_once "WxPay.Api.php";
require_once 'WxPay.Notify.php';
require_once 'log.php';  

//初始化日志

$logHandler= new CLogFileHandler("../logs/".date('Y-m-d-H-i-s').'.log');
$log = Log::Init($logHandler, 15); 
 
class PayNotifyCallBack extends WxPayNotify
{
	//查询订单
	var $xsuccess='';
	public function Queryorder($transaction_id)
	{
		$input = new WxPayOrderQuery();
		$input->SetTransaction_id($transaction_id);
		$result = WxPayApi::orderQuery($input);
		Log::DEBUG("query:" . json_encode($result));
		if(array_key_exists("return_code", $result)
			&& array_key_exists("result_code", $result)
			&& $result["return_code"] == "SUCCESS"
			&& $result["result_code"] == "SUCCESS")
		{
			return true;
		}
		//print_r($result);
		return false;
	}
	
	//重写回调处理函数
	public function NotifyProcess($data, &$msg)
	{
		global $dsql;
		Log::DEBUG("call back:" . json_encode($data));
		$notfiyOutput = array();
		
		if(!array_key_exists("transaction_id", $data)){
			$msg = "输入参数不正确";
			return false;
		}
		//查询订单，判断订单真实性
		if(!$this->Queryorder($data["transaction_id"])){
			$msg = "订单查询失败";
			return false;
		}
		
		Log::DEBUG($data['transaction_id'].'xiexiang');
		$orderID=$data['out_trade_no'];
		$wx_orderID=$data['transaction_id'];
		 $sql = "UPDATE `#@__shops_orders` SET `state`='1' WHERE `oid`='$orderID'";

		if($data['result_code']=='SUCCESS' && $dsql->ExecuteNoneQuery($sql)){
		      Log::DEBUG("UPDATE `#@__shops_orders` SET `state`='1' WHERE `oid`='$orderID' ");
			  $this->xsuccess=$data['result_code'];
			 //$dsql->ExecuteNoneQuery(" UPDATE `#@__baoming` SET fk_state=1,zf_orderID='$wx_orderID',zf_fangshi='微信支付' WHERE orderID='$orderID' ");
			 echo "<script type='text/javascript'>alert('支付成功·正在跳转会员中心...');window.location.href  = '/member/';	</script>";
			 ShowMsg("支付成功!<br> <a href='/'>返回主页</a> <a href='/member'>会员中心</a>", "javascript:;", 0, 3000);
			return true;
		}else{
			Log::DEBUG("UPDATE `#@__shops_orders` SET `state`='1' WHERE `oid`='$orderID' ");
		 	ShowMsg("支付失败！<br> <a href='/'>返回主页</a> <a href='/member'>会员中心</a>", "javascript:;", 0, 3000);
			return false;
		}
		//Log::DEBUG(" UPDATE `#@__baoming` SET fk_state=1,zf_orderID='$wx_orderID',zf_fangshi='微信支付' WHERE orderID='$orderID' ");
		
	}
}

Log::DEBUG("begin notify 失败了");
$notify = new PayNotifyCallBack();
$notify->Handle(false);


